const Router = require('koa-router')
const sequelize=require("../../core/db")
const {Group,User} = require('../../model/index')
const auth = require("../../middleware/auth")
const { Success, CustomError, generateToken, generateRefreshToken, setCookie } = require('../../core/common')
const { ParameterError } = require('../../config/errorCode')
const router = new Router({
    prefix: '/v1/register'
})

// 注册
router.post('/addUser', async (ctx) => {
    const { phone, password, nickName } = ctx.request.body
    const userExist = await User.findOne({ where: { phone } })
    if (userExist) {
        throw new CustomError('手机号已注册', ParameterError)
    }
    const nickNameUser = await User.findOne({ where: { nickName } })
    if (nickNameUser) {
        throw new CustomError('改昵称已注册', ParameterError)
    }
    //托管事务
    await sequelize.transaction(async (t) => {
        const user = await User.create({ phone, password,nickName},{ transaction: t})
        // 生成默认分组
        const groupList = await Group.bulkCreate([
            { name: '全部关注', type: 1 },
            { name: '最新微博', type: 1 },
            { name: '特别关注', type: 1 },
            { name: '好友圈', type: 1 },
            { name: '原创', type: 1 },
            { name: '视频', type: 1 },
            { name: 'V+微博', type: 1 },
            { name: '群微博', type: 1 },
            { name: '悄悄关注', type: 2 },
            { name: '同学', type: 2, canDel: true },
            { name: '名人明星', type: 2, canDel: true },
            { name: '同事', type: 2, canDel: true }
        ],{ transaction: t})
        await user.addGroup(groupList,{ transaction: t})
        const token = generateToken(user.uid)
        const refreshToken = generateRefreshToken(user.uid)
        // 服务端渲染时无法使用localStorage，使用cookie代替
        setCookie(ctx, 'access_token', token)
        setCookie(ctx, 'refresh_token', refreshToken)
    
        Success(ctx,user.userInfo)
     })
})
//判断昵称是否存在 
router.get("/nickNameExist", async ctx => {
    const { nickName } = ctx.request.query
    const user = await User.findOne({
        where: {
            nickName
        }
    })
    if (user) {
        Success(ctx, { nickNameExist: true })
    }
    else {
        Success(ctx, { nickNameExist: false })
    }
})
//删除用户(测试使用)
if (process.env.NODE_ENV == "test") {
    router.del("/removeUser", auth, async ctx => {
        const { user } = ctx.auth
        const delItem = await user.destroy();
        if (delItem) {
            Success(ctx)
        }
        else {
            throw new CustomError("删除失败", 402)
        }
    })
}
module.exports = router
